package com.Humanities.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.Humanities.content.mapper.CourseBaseMapper;
import com.Humanities.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseTeacher;
import com.Humanities.content.service.ICourseTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程-教师关系表 服务实现类
 * </p>
 *
 * @author ysj
 * @since 2025-03-26
 */
@Service
 public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements ICourseTeacherService {
    @Autowired
    private CourseTeacherMapper courseTeacherMapper;
    @Autowired
    private CourseBaseMapper courseBaseMapper;

    /**
     * 查询课程教师
     * @param courseId 课程id
     * @return List<CourseTeacher>
     */

    public List<CourseTeacher> getTeacherInfo(Long courseId) {
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(CourseTeacher::getCourseId, courseId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(queryWrapper);
        return courseTeachers;
    }

    /**
     * 新增或者修改教师信息
     * @param companyId
     * @param courseTeacher
     * @return
     */
    @Override
    public CourseTeacher saveOrUpdate(Long companyId, CourseTeacher courseTeacher) {

        CourseBase courseBase = courseBaseMapper.selectById(courseTeacher.getCourseId());
        if (courseBase == null || !companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast("课程不存在或机构只能修改自己的教师信息");
        }
        if (courseTeacher.getId() == null){
            //新增教师
            courseTeacherMapper.insert(courseTeacher);
            return courseTeacher.setId(courseTeacher.getId());
        }else {
            courseTeacherMapper.updateById(courseTeacher);
            return courseTeacher.setId(courseTeacher.getId());
        }


    }

    /**
     * 删除课程教师
     * @param courseId
     * @param id
     */
    @Override
    public void deleteCourseTeacher(Long companyId,Long courseId, Long id) {
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null || !companyId.equals(courseBase.getCompanyId())){

            throw new XueChengPlusException("课程不存在或本机构只能删除本机构的教师");
        }
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId);
        queryWrapper.eq(CourseTeacher::getId,id);
        int delete = courseTeacherMapper.delete(queryWrapper);
        if (delete<=0){
            XueChengPlusException.cast("删除教师失败");
        }

    }
}
